package jevon.philautus.injector;

import java.lang.reflect.Field;

import jevon.philautus.stereotype.Log;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;



/**
 * 日志注入器
 * @author fujinjun
 *
 */
@Component("loggerInjector")
public class LoggerInjector implements BeanPostProcessor{

	@Override
	public Object postProcessAfterInitialization(Object bean, String arg1)
			throws BeansException {
		return bean;
	}

	@Override
	public Object postProcessBeforeInitialization(final Object bean, String beanName)
			throws BeansException {
		ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {

			@Override
			public void doWith(Field field) throws IllegalArgumentException,
					IllegalAccessException {
				ReflectionUtils.makeAccessible(field);
				if (field.getAnnotation(Log.class) != null) {
					String name = bean.getClass().getName();
					org.apache.log4j.Logger logger = org.apache.log4j.Logger
							.getLogger(name);
					field.set(bean, logger);

				}
			}
		});
		return bean;
	}

}